<?php

namespace app\api\controller;

use think\Controller;
use think\facade\App;

class Pay extends Auth
{

    public function __construct()
    {
        parent::__construct();
    }

    public function paymentTransaction()
    {
        $post = input('post.');

        if (empty($post['orderid'])) {
            return $this->json([], 2000, '订单号必传');
        }

        $where = [
            'orderid' => $post['orderid'],
        ];

        $info = $this->findTable('order', ['where' => $where]);

        if (empty($info)) {
            return $this->json([], 2000, '订单不存在，请确认');
        }

        if ($info['status'] < 2) {
            return $this->json([], 2000, '请选择教练后再操作');
        }

        if ($info['status'] > 3) {
            return $this->json([], 2000, '订单已支付');
        }

        $wechat = new \WeChat\Pay(config('pay.wxpay'));
        $options = [
            'body' => $info['ordername'] . $info['collegemobile'],
            'out_trade_no' => $info['ordersn'],
            'total_fee' => $post['payamount'],
            'trade_type' => 'APP',
            'notify_url' => \think\facade\Request::baseFile(true) . '/api/notify/wxpaynotify',
            'spbill_create_ip' => get_ip(),
        ];

        try {
            // 生成预支付码
            $result = $wechat->createOrder($options);

            if (empty($result)) {
                return $this->json([], 2000, '支付创建失败');
            }

            if ($result['result_code'] != 'SUCCESS' && isset($result['err_code'])) {
                $msg = empty($result['err_code_des']) ? '支付发起失败' : $result['err_code_des'];
                return $this->json([], 2000, $msg);
            }

            if (empty($result['prepay_id'])) {
                return $this->json([], 2000, '支付发起失败');
            }

            // 创建APP参数签名
            $options = $wechat->createParamsForApp($result['prepay_id']);

            $data = [
                'payamount' => $info['amount'],
                'memberid' => $info['memberid'],
                'orderid' => $info['orderid'],
                'ordersn' => $info['ordersn'],
                'revision' => 0,
                'paymentid' => $result['prepayid'],
                'commodityname' => $options['body'],
            ];

            $ans = $this->insertTable('payment_transaction', $data);

            if($ans) {
                return $this->json($result, 1000);
            } else {
                return $this->json([], 2000, '支付发起失败');
            }


        } catch (\Exception $e) {
            return $this->json([], 2000, $e->getMessage());
        }
    }

    public function reward()
    {
        if ($this->role != 1) {
            $this->initreturn('越权操作');
        }

        $post = input('post.');

        if (empty($post['orderid'])) {
            return $this->json([], 2000, '订单号必传');
        }

        if (empty($post['payamount']) || floatval($post['payamount']) <= 0) {
            return $this->json([], 2000, '请输入打赏金额');
        }

        $where = [
            'orderid' => $post['orderid'],
        ];

        $info = $this->findTable('order', ['where' => $where]);

        if (empty($info)) {
            return $this->json([], 2000, '打赏订单不存在，请确认');
        }

        if ($info['status'] != 7) {
            return $this->json([], 2000, '评价后才能打赏');
        }
        $rewardsn = $this->buildSn();
        $wechat = new \WeChat\Pay(config('pay.wxpay'));
        $options = [
            'body' => $info['ordername'] . $info['collegemobile'],
            'out_trade_no' => $rewardsn,
            'total_fee' => $post['payamount'],
            'trade_type' => 'APP',
            'notify_url' => \think\facade\Request::baseFile(true) . '/api/notify/wxpayreward',
            'spbill_create_ip' => get_ip(),
        ];

        try {
            // 生成预支付码
            $result = $wechat->createOrder($options);

            if (empty($result)) {
                return $this->json([], 2000, '支付创建失败');
            }

            if ($result['result_code'] != 'SUCCESS' && isset($result['err_code'])) {
                $msg = empty($result['err_code_des']) ? '支付发起失败' : $result['err_code_des'];
                return $this->json([], 2000, $msg);
            }
            if (empty($result['prepay_id'])) {
                return $this->json([], 2000, '支付发起失败');
            }

            // 创建APP参数签名
            $param = $wechat->createParamsForApp($result['prepay_id']);

            $data = [
                'payamount' => $post['payamount'],
                'memberid' => $info['memberid'],
                'coachid' => $info['coachid'],
                'orderid' => $info['orderid'],
                'rewardsn' => $rewardsn,
                'revision' => 0,
                'paymentid' => $result['prepay_id'],
                'commodityname' => $options['body'],
            ];

            $ans = $this->insertTable('reward', $data);

            if($ans) {
                return $this->json($result, 1000);
            } else {
                return $this->json([], 2000, '支付发起失败');
            }


        } catch (\Exception $e) {
            return $this->json([], 2000, $e->getMessage());
        }
    }


}
